import React, { Component, useState } from "react";
import { View, ScrollView, Text } from "@tarojs/components";
import { AtIcon } from "taro-ui";
import "./component.less";
import { formatDate } from "./modal";

type XScrollPickerProps = {
    data: any[],
    value: number,
    onChange?: (value: number) => any
    width?: number
    left?: number
}

type XScrollPickerState = {
}

export class XScrollPicker extends Component<XScrollPickerProps, XScrollPickerState> {
    node: HTMLDivElement;
    X: number;
    flag: boolean;
    select: number;
    constructor(props: XScrollPickerProps) {
        super(props);
        this.flag = false;
        this.select = props.value;
    }

    onMoveStart(e: React.MouseEvent) {
        this.X = e.clientX;
        this.flag = true;
    }
    onMove(e: React.MouseEvent) {
        if (this.flag) {
            let x = this.X - e.clientX;
            if (this.node.scrollLeft >= 0 && this.node.scrollLeft < this.node.scrollWidth) {
                this.node.scrollTo({ left: this.node.scrollLeft + x });
                this.X = e.clientX;
            }
        }
    }

    onMoveEnd(e: React.MouseEvent) {
        this.flag = false;
    }

    render() {
        return (
            <div
                ref={(node) => { this.node = node }}
                className="pcy-scroll-x"
                style={{
                    position: "relative",
                    height: "2rem",
                    borderBottom: "1px solid #eee",
                }}
                onMouseDown={this.onMoveStart.bind(this)}
                onMouseMove={this.onMove.bind(this)}
                onMouseUp={this.onMoveEnd.bind(this)}
                onMouseLeave={this.onMoveEnd.bind(this)}
            >
                <View style={{
                    display: "flex",
                    position: "absolute",
                    padding: "0 1rem 0 0.1rem",
                }}>
                    {this.props.data.map((item, index) => {
                        return <View
                            className="year-piker-item"
                            onClick={() => {
                                if (this.props.onChange && this.select !== index) {
                                    this.select = index;
                                    this.props.onChange(index);
                                }
                            }}
                            style={{
                                width: `${this.props.width ? this.props.width : 3}rem`,
                                textAlign: "center",
                                fontSize: "0.6rem",
                                color: "#666",
                                height: "2rem",
                                lineHeight: "2rem"
                            }}
                        >
                            {"" + item}
                        </View>
                    })}

                </View>
                <View
                    className="line"
                    style={{
                        position: "absolute",
                        left: `${0.4 + this.props.value * (this.props.width ? this.props.width : 3)}rem`,
                        bottom: "0px",
                        width: `${this.props.width ? this.props.width - 0.6 : 2.4}rem`,
                        height: "3px",
                        transition: "all 0.2s ease",
                    }}
                />
            </div>
        )
    }
}


export type AgreedData = {
    aid: number
    uid: string
    mid: number
    start_time: number
    end_time: number
    reason: string
    note: string
    status: string
    approver: string //审批人
    group?: number
    area: number
    authority: number
    department: string
    mname: string
    uname: string
    wifi: number
    refuse_reason: string
}

type ApproveItemProps = {
    data: AgreedData
    onClick?: () => any
    footer?: React.ReactNode
}

enum status {
    "wait" = "等待中",
    "refuse" = "已拒绝",
    "pass" = "已通过",
    "timeout" = "已超时",
    "revoke" = "已撤销"
}

enum color {
    "wait" = "#014A95",
    "refuse" = "#ee6e6e",
    "pass" = "#88e66b",
    "timeout" = "#ffce49",
    "revoke" = "#888"
}

export class ApproveStatusText extends Component<{ status: string }, any> {
    constructor(props) {
        super(props);
    }

    render() {
        return <Text style={{ color: color[this.props.status] }}>{status[this.props.status]}</Text>
    }
}

export class ApproveItem extends Component<ApproveItemProps, any> {
    constructor(props: ApproveItemProps) {
        super(props);
    }

    render() {
        return (
            <div
                className="my-Approve-item"
                onClick={this.props.onClick}
            >
                <View
                    className="approve-item-card-header"
                    style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        backgroundColor: color[this.props.data.status]
                    }}>
                    <View style={{ fontSize: "0.8rem" }}>{this.props.data.mname}</View>
                    <View style={{ fontSize: "0.5rem" }}>{status[this.props.data.status]}</View>
                </View>
                <View className="approve-item-card-body">
                    <View style={{
                        display: "flex",
                        justifyContent: "space-between"
                    }}>
                        <View className="approve-text-not-primary">申请时间：{formatDate(new Date(this.props.data.start_time), "yyyy年MM月dd日")}</View>
                        {this.props.data.uname ? <View className="approve-text-not-primary">申请人：{this.props.data.uname}</View> : ""}
                    </View>
                    <View
                        className="time"
                        style={{
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center"
                        }}
                    >
                        <View className="hour-min">{formatDate(new Date(this.props.data.start_time), "HH:mm")}</View>
                        <div style={{
                            width: "2rem",
                            height: "3px",
                            backgroundColor: "#222"
                        }}></div>
                        <View className="hour-min">{formatDate(new Date(this.props.data.end_time), "HH:mm")}</View>
                    </View>
                    <View className="approve-text-not-primary">申请理由：{this.props.data.reason}</View>
                    {this.props.data.status === "refuse"?<View className="approve-text-not-primary">拒绝理由：{this.props.data.refuse_reason}</View>:""}
                    
                </View>
                <View>
                    {this.props.footer}
                </View>
            </div>
        )
    }
}

type CalendarProps = {
    min?: Date,
    max?: Date,
    defaultValue?: Date
    mode?: "week" | "month"
    onChange?: (date: Date) => any
}

export const Calendar: React.FC<CalendarProps> = (props) => {
    const [date, setDate] = useState(props.defaultValue ? props.defaultValue : (props.min ? props.min : new Date()));
    const [left, setLeft] = useState(!(props.min && formatDate(date, "yyyy-MM-dd") <= formatDate(props.min, "yyyy-MM-dd")));
    const [right, setRight] = useState(!(props.max && formatDate(date, "yyyy-MM-dd") >= formatDate(props.max, "yyyy-MM-dd")));


    const handleClickToggleDateView = (direction: "left" | "right") => {
        if (direction === "left" && left) {
            let time = date.getTime();
            time -= 1000 * 60 * 60 * 24 * 7;
            setDate(() => {
                if (props.min && formatDate(new Date(time), "yyyy-MM-dd") <= formatDate(props.min, "yyyy-MM-dd")) {
                    setLeft(false);
                } else {
                    setRight(true);
                }
                return new Date(time);
            });
            if (props.onChange) {
                props.onChange(new Date(time));
            }
        } else if (direction === "right" && right) {
            let time = date.getTime();
            time += 1000 * 60 * 60 * 24 * 7;
            setDate(() => {
                if (props.max && formatDate(new Date(time), "yyyy-MM-dd") >= formatDate(props.max, "yyyy-MM-dd")) {
                    setRight(false);
                } else {
                    setLeft(true)
                }
                return new Date(time);
            });
            if (props.onChange) {
                props.onChange(new Date(time));
            }
        }

    }

    return (
        <View className="calendar">
            <View className="calendar-header">
                <View
                    className="calendar-header-item left-btn"
                    onClick={() => {
                        handleClickToggleDateView("left")
                    }}>
                    <AtIcon value='chevron-left' size='20' color={left ? "#000" : "#fff"}></AtIcon>
                </View>

                <View className="calendar-header-item">{date.getFullYear()}年{date.getMonth() + 1}月</View>
                <View
                    className="calendar-header-item right-btn"
                    onClick={() => {
                        handleClickToggleDateView("right")
                    }}>
                    <AtIcon value='chevron-right' size='20' color={right ? "#000" : "#fff"}></AtIcon>
                </View>
            </View>
            <View className="calendar-body">
                <View className="calendar-line calendar-week">
                    <View className="calendar-item">一</View>
                    <View className="calendar-item">二</View>
                    <View className="calendar-item">三</View>
                    <View className="calendar-item">四</View>
                    <View className="calendar-item">五</View>
                    <View className="calendar-item">六</View>
                    <View className="calendar-item">日</View>
                </View>
                {((): React.ReactNode[] => {
                    if (props.mode === "week") {
                        let rtn = [];
                        let day = date.getDay();
                        let end = 1 - day + 7;
                        for (let i = 1 - day; i < end; i++) {
                            let time = date.getTime();
                            let temp = new Date(time + (i * 1000 * 60 * 60 * 24));
                            rtn.push(<View key={formatDate(temp, "yyyy-MM-dd")} className={`calendar-item ${formatDate(temp, "yyyy-MM-dd") === formatDate(new Date(), "yyyy-MM-dd") ? "select" : ""}`}>{temp.getDate()}</View>);
                        }
                        return [<View className="calendar-line" key={"day"}>{rtn}</View>]
                    }
                })()}
            </View>
        </View>
    )
}

type timeAxisGroupProps = {
    min?: number
    max?: number
}

export const TimeAxisGroup: React.FC<timeAxisGroupProps> = (props) => {
    const anhour = 100;
    let min = props.min ? props.min : 0;
    let max = props.max ? props.max : 24;
    return (
        <View className="time-axis-box" style={{ height: ((max - min) * anhour) + "px" }}>
            <View className="time-axis-times">
                {((): React.ReactNode[] => {
                    let nodes = [];
                    for (let i = 0; i <= max - min; i++) {
                        nodes.push(
                            <View
                                className="time-axis-times-item"
                                style={{
                                    top: i * anhour + "px",
                                    lineHeight: "0"
                                }}
                                key={"times" + i}
                            >
                                {(i + min < 10 ? `0${i + min}` : i + min)}
                            </View>
                        )
                    }
                    return nodes;
                })()}
            </View>
            <View className="time-axis-body">
                {props.children}
            </View>
        </View>
    )
}

type timeAxisProps = {
    data?: { start: Date, end: Date }[],
    min?: number
    max?: number
}

export const TimeAxis: React.FC<timeAxisProps> = (props) => {
    const anhour = 100;
    let min = props.min ? props.min : 0;
    let max = props.max ? props.max : 24;
    return (
        <View style={{
            height: "100%",
            width: "100%",
            position: "relative",
            borderLeft: "1px solid #ddd",
        }}>
            {props.data ? props.data.map((item, index) => {
                return (
                    <View
                        key={"axis" + index}
                        className="time-data-box"
                        style={{
                            height: `${((item.end.getHours() - item.start.getHours()) * anhour + (item.end.getMinutes() - item.start.getMinutes()) * anhour / 60)}px`,
                            top: `${((item.start.getHours() - props.min) * anhour + item.start.getMinutes() * anhour / 60)>0?((item.start.getHours() - props.min) * anhour + item.start.getMinutes() * anhour / 60):0}px`,
                        }}
                    >
                        <View style={{position: "absolute", top: 0, textAlign: "center", width: "100%"}}>
                            {formatDate(item.start, "HH:mm")}
                        </View>
                        <View  style={{position: "absolute", bottom: 0, textAlign: "center",  width: "100%"}}>
                            {formatDate(item.end, "HH:mm")}
                        </View>

                    </View>
                )
            }) : ""}
        </View>
    )
}